<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录</title>
    <style>
        body {
            font-family: sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background-color: #f4f4f4;
        }
        #login-container {
            background-color: #fff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 400px;
        }
        h2 {
            text-align: center;
            margin-bottom: 25px;
            color: #333;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-weight: bold;
        }
        input[type="text"],
        input[type="password"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }
        #loginButton {
            width: 100%;
            padding: 12px;
            background-color: #007bff; /* Blue for primary action */
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s ease;
            margin-bottom: 10px; /* Add space below login button */
        }
        #loginButton:hover {
            background-color: #0056b3;
        }
        #loginButton:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        #errorMessage {
            color: #dc3545;
            margin-top: 15px;
            text-align: center;
            min-height: 1.2em;
            font-weight: bold;
        }

        /* --- Style for the Register Button (Link) --- */
        #registerLink {
            display: block; /* Make it block level for full width & margin control */
            width: 100%;
            padding: 10px; /* Slightly smaller padding than login */
            background-color: #6c757d; /* Gray for secondary action */
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px; /* Slightly smaller font */
            text-align: center; /* Center text */
            text-decoration: none; /* Remove underline from link */
            transition: background-color 0.3s ease;
            margin-top: 10px; /* Space above the register button */
            box-sizing: border-box;
        }

        #registerLink:hover {
            background-color: #5a6268;
        }
        /* --- End of Register Button Style --- */

    </style>
</head>
<body>

<div id="login-container">
    <h2>用户登录</h2>
    <form id="loginForm">
        <div class="form-group">
            <label for="username">用户名:</label>
            <input type="text" id="username" name="username" required>
        </div>
        <div class="form-group">
            <label for="password">密码:</label>
            <input type="password" id="password" name="password" required>
        </div>
        <button type="submit" id="loginButton">登录</button>
        <!-- Error message div moved slightly down conceptually -->
        <div id="errorMessage"></div>
    </form>

    <!-- === Add Register Button (as a link) Below the Form === -->
    <a href="signup.html" id="registerLink">没有账号？前往注册</a>
    <!-- ====================================================== -->

</div>

<script>
    const loginForm = document.getElementById('loginForm');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const loginButton = document.getElementById('loginButton');
    const errorMessageDiv = document.getElementById('errorMessage');
    // No need for JavaScript for the registerLink, it's a standard hyperlink

    loginForm.addEventListener('submit', async (event) => {
        event.preventDefault();

        const username = usernameInput.value.trim();
        const password = passwordInput.value.trim();

        if (!username || !password) {
            errorMessageDiv.textContent = '用户名和密码不能为空！';
            return;
        }

        errorMessageDiv.textContent = '';
        loginButton.disabled = true;
        loginButton.textContent = '登录中...';

        const loginData = {
            username: username,
            password: password
        };

        try {
            const response = await fetch('/index/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(loginData)
            });

            const result = await response.json();

            if (!response.ok) {
                errorMessageDiv.textContent = `登录失败: ${result?.msg || response.statusText || '服务器错误'}`;
                // Keep button disabled on error to avoid immediate resubmit
                // loginButton.disabled = false; // Keep disabled
                loginButton.textContent = '登录'; // Reset button text
                return; // Stop further processing
            }

            if (result.code === 1 && result.data && result.data.token) {
                errorMessageDiv.textContent = '';
                // alert('登录成功！即将跳转到上传页面...'); // Optional alert

                // Store token if needed
                // localStorage.setItem('authToken', result.data.token);
                // sessionStorage.setItem('authToken', result.data.token);

                window.location.href = 'upload.html'; // Redirect on success

            } else {
                errorMessageDiv.textContent = `登录失败: ${result.msg || '无效的用户名或密码'}`;
                loginButton.disabled = false; // Re-enable on logical failure
                loginButton.textContent = '登录';
            }

        } catch (error) {
            console.error('登录过程中发生错误:', error);
            if (!errorMessageDiv.textContent) {
                errorMessageDiv.textContent = '登录请求失败，请检查网络连接或稍后再试。';
            }
            loginButton.disabled = false; // Re-enable on network/fetch error
            loginButton.textContent = '登录';
        }
        // No finally block needed here specifically for the button re-enabling,
        // handled within try/catch based on outcome.
    });
</script>

</body>
</html>